import React, { useState } from 'react';
import { getAllMissions, getMissionTypes } from '../utils/MissionScenarios';
import './MissionControl.css';

const MissionControl = ({
  flightController,
  onMissionStart,
  onMissionStop,
  flightState,
  isVisible = true
}) => {
  const [selectedMission, setSelectedMission] = useState(null);
  const [selectedType, setSelectedType] = useState('all');
  const [showManualControls, setShowManualControls] = useState(false);
  const [isCollapsed, setIsCollapsed] = useState(false);

  if (!isVisible) return null;

  const missions = getAllMissions();
  const missionTypes = getMissionTypes();

  const filteredMissions = selectedType === 'all'
    ? missions
    : missions.filter(mission => mission.type === selectedType);

  const handleMissionSelect = (mission) => {
    setSelectedMission(mission);
  };

  const handleStartMission = () => {
    if (selectedMission && onMissionStart) {
      onMissionStart(selectedMission);
    }
  };

  const handleStopMission = () => {
    if (onMissionStop) {
      onMissionStop();
    }
  };

  const handleTakeOff = () => {
    if (flightController) {
      flightController.takeOff();
    }
  };

  const handleLand = () => {
    if (flightController) {
      flightController.land();
    }
  };

  const handleEmergencyStop = () => {
    if (flightController) {
      flightController.emergencyStop();
    }
  };

  // Manual control handlers
  const handleKeyDown = (input) => {
    if (flightController) {
      flightController.setInput(input, true);
    }
  };

  const handleKeyUp = (input) => {
    if (flightController) {
      flightController.setInput(input, false);
    }
  };

  return (
    <div className={`mission-control ${isCollapsed ? 'collapsed' : ''}`}>
      <div className="mission-header" onClick={() => setIsCollapsed(!isCollapsed)}>
        <h2>🎯 Mission Control</h2>
        <span className={`collapse-arrow ${isCollapsed ? 'collapsed' : ''}`}>▼</span>
      </div>

      {!isCollapsed && (
        <div className="mission-content">
          <div className="control-tabs">
            <button
              className={`tab ${!showManualControls ? 'active' : ''}`}
              onClick={() => setShowManualControls(false)}
            >
              Missions
            </button>
            <button
              className={`tab ${showManualControls ? 'active' : ''}`}
              onClick={() => setShowManualControls(true)}
            >
              Manual
            </button>
          </div>

      {!showManualControls ? (
        <>
          {/* Mission Selection */}
          <div className="mission-section">
            <h3>Available Missions</h3>

            <div className="mission-filter">
              <label>Filter by type:</label>
              <select
                value={selectedType}
                onChange={(e) => setSelectedType(e.target.value)}
              >
                <option value="all">All Types</option>
                {missionTypes.map(type => (
                  <option key={type} value={type}>
                    {type.charAt(0).toUpperCase() + type.slice(1)}
                  </option>
                ))}
              </select>
            </div>

            <div className="mission-list">
              {filteredMissions.map(mission => (
                <div
                  key={mission.id}
                  className={`mission-item ${selectedMission?.id === mission.id ? 'selected' : ''}`}
                  onClick={() => handleMissionSelect(mission)}
                >
                  <div className="mission-name">{mission.name}</div>
                  <div className="mission-type">{mission.type}</div>
                  <div className="mission-duration">{mission.duration}s</div>
                </div>
              ))}
            </div>
          </div>

          {/* Mission Details */}
          {selectedMission && (
            <div className="mission-section">
              <h3>Mission Details</h3>
              <div className="mission-details">
                <h4>{selectedMission.name}</h4>
                <p>{selectedMission.description}</p>
                <div className="mission-stats">
                  <span>Type: {selectedMission.type}</span>
                  <span>Duration: {selectedMission.duration}s</span>
                  <span>Waypoints: {selectedMission.waypoints.length}</span>
                </div>
              </div>
            </div>
          )}

          {/* Mission Controls */}
          <div className="mission-section">
            <h3>Mission Controls</h3>
            <div className="mission-controls">
              <button
                className="control-btn start"
                onClick={handleStartMission}
                disabled={!selectedMission || flightState?.autopilot}
              >
                🚀 Start Mission
              </button>

              <button
                className="control-btn stop"
                onClick={handleStopMission}
                disabled={!flightState?.autopilot}
              >
                ⏹️ Stop Mission
              </button>
            </div>
          </div>
        </>
      ) : (
        <>
          {/* Manual Flight Controls */}
          <div className="mission-section">
            <h3>Flight Controls</h3>
            <div className="flight-controls">
              <button
                className="control-btn takeoff"
                onClick={handleTakeOff}
                disabled={flightState?.isFlying}
              >
                🛫 Take Off
              </button>

              <button
                className="control-btn land"
                onClick={handleLand}
                disabled={!flightState?.isFlying}
              >
                🛬 Land
              </button>

              <button
                className="control-btn emergency"
                onClick={handleEmergencyStop}
              >
                🚨 Emergency Stop
              </button>
            </div>
          </div>

          {/* Manual Movement Controls */}
          <div className="mission-section">
            <h3>Movement Controls</h3>
            <div className="movement-controls">
              <div className="control-instructions">
                <p>🎮 Keyboard Controls (Primary):</p>
                <ul>
                  <li><strong>Arrow Keys</strong> or <strong>WASD</strong>: Move Forward/Back/Left/Right</li>
                  <li><strong>Space</strong> or <strong>R</strong>: Ascend (Up)</li>
                  <li><strong>Shift</strong> or <strong>F</strong>: Descend (Down)</li>
                  <li><strong>Q/E</strong>: Rotate Left/Right</li>
                  <li><strong>T</strong>: Take Off | <strong>L</strong>: Land | <strong>ESC</strong>: Emergency Stop</li>
                </ul>
                <p>💡 <em>Hold keys for continuous movement. Use buttons below as backup.</em></p>
              </div>

              <div className="control-grid">
                <div className="control-row">
                  <button
                    className="movement-btn"
                    onMouseDown={() => handleKeyDown('up')}
                    onMouseUp={() => handleKeyUp('up')}
                    onMouseLeave={() => handleKeyUp('up')}
                  >
                    ⬆️ Up
                  </button>
                </div>

                <div className="control-row">
                  <button
                    className="movement-btn"
                    onMouseDown={() => handleKeyDown('rotateLeft')}
                    onMouseUp={() => handleKeyUp('rotateLeft')}
                    onMouseLeave={() => handleKeyUp('rotateLeft')}
                  >
                    ↺ Left
                  </button>

                  <button
                    className="movement-btn"
                    onMouseDown={() => handleKeyDown('forward')}
                    onMouseUp={() => handleKeyUp('forward')}
                    onMouseLeave={() => handleKeyUp('forward')}
                  >
                    ⬆️ Forward
                  </button>

                  <button
                    className="movement-btn"
                    onMouseDown={() => handleKeyDown('rotateRight')}
                    onMouseUp={() => handleKeyUp('rotateRight')}
                    onMouseLeave={() => handleKeyUp('rotateRight')}
                  >
                    ↻ Right
                  </button>
                </div>

                <div className="control-row">
                  <button
                    className="movement-btn"
                    onMouseDown={() => handleKeyDown('left')}
                    onMouseUp={() => handleKeyUp('left')}
                    onMouseLeave={() => handleKeyUp('left')}
                  >
                    ⬅️ Left
                  </button>

                  <button
                    className="movement-btn"
                    onMouseDown={() => handleKeyDown('backward')}
                    onMouseUp={() => handleKeyUp('backward')}
                    onMouseLeave={() => handleKeyUp('backward')}
                  >
                    ⬇️ Back
                  </button>

                  <button
                    className="movement-btn"
                    onMouseDown={() => handleKeyDown('right')}
                    onMouseUp={() => handleKeyUp('right')}
                    onMouseLeave={() => handleKeyUp('right')}
                  >
                    ➡️ Right
                  </button>
                </div>

                <div className="control-row">
                  <button
                    className="movement-btn"
                    onMouseDown={() => handleKeyDown('down')}
                    onMouseUp={() => handleKeyUp('down')}
                    onMouseLeave={() => handleKeyUp('down')}
                  >
                    ⬇️ Down
                  </button>
                </div>
              </div>
            </div>
          </div>
        </>
      )}
        </div>
      )}
    </div>
  );
};

export default MissionControl;
